package net.ib.mtalk.ui.attachment.vcalendar;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseListActivity;
import net.ib.mtalk.ui.attachment.vcalendar.VCalendarStruct.EventStruct;
import net.ib.mtalk.util.TimeAdapter;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * Project Name: mnTalk
 * @CalendarListActivity.java
 * @author	happy2v@infobank.net (A70M)
 * @version 0.1
 * @since	10/12/14
 * @history
 *   - 
 * 
 */
public class VCalendarListActivity extends BaseListActivity {
	
	public static final String INTENT_VCALENDAR_CONTENT = "vcalendar_content";
	public static final String INTENT_VCALENDAR_FILE_NAME = "vcalendar_file_name";
	
//	private Map<Integer, CalendarList> cal_checkedIdMgr	= null;
	private static int 				eventCount 			= 0;
	public VCalendarListAdapter 	cal_adapter 		= null;
	private static VCalendarStruct	calFileStruct		= null;
	private static EventStruct[] 	calEvents 			= null;
	private static String[] 		calCalendarIds 		= null;
	private static String 			vcalString 			= null;	
	private static String 			dateString			= null;
	private static String 			dateSendString		= null;
	private List<VCalendarList> cal_items = new ArrayList<VCalendarList>();;
	String searchable ="";
	private String fileName;
	
	int toastStrId = -1;
	Context ctx;
	
	public ListView calendarList;
	
	ProgressDialog progressDialog;
	final private int PROGRESS_DIALOG = 0;
	
	public static String				EXTRA_VCALENDAR		= "extra vcalendar";
	public static String 				EXTRA_FILEKEY 		= "extra filekey"; 
	public static String 				EXTRA_FILEURI 		= "extra fileuri"; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.layout_multimedia_vcalendar_send);

		ctx = this;
		
//		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//		cal_checkedIdMgr = new HashMap<Integer, CalendarList>();
		
		LoadCalEvent(this);
		if(eventCount == 0){
			toastStrId = R.string.toast_calendar_not_found;
//			Toast.makeText(ctx, "Calendar events can be found.", Toast.LENGTH_SHORT).show();
			finish();
		}
		this.cal_items = ViewListCalendar(cal_items);

//		this.registerForContextMenu(getListView());
	}
	
	private void submitResult(String fileContent, String fileName) {
		Intent intent = new Intent();
		intent.putExtra(INTENT_VCALENDAR_CONTENT, fileContent);
		intent.putExtra(INTENT_VCALENDAR_FILE_NAME, fileName);
		if (fileContent == null) {
			setResult(RESULT_CANCELED, intent);
		} else {
			setResult(RESULT_OK, intent);
		}
		finish();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		updateList();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		calFileStruct = new VCalendarStruct();
		calFileStruct.addEventList(calEvents[position]);
		
		if(calEvents[position].title != null){
			dateSendString = calEvents[position].title;
		}
		File checkSDCardDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
		if(!checkSDCardDirectory.canRead()){
			toastStrId = R.string.toast_sdcard_not_found;
		}else{
			showDialog(PROGRESS_DIALOG);
			Thread thread = new Thread(null, sendCalendar);
			thread.start();
		}
	}
	
	public void updateList() {
		if (cal_items != null && cal_items.size() > 0) {
			refreshHandler.sendMessage(refreshHandler.obtainMessage());
		}
	}
	public final Handler refreshHandler = new Handler() {
		public synchronized void handleMessage(Message msg) {
			refreshAdapter();
		}
	};
	public void refreshAdapter() {
		cal_adapter = new VCalendarListAdapter(this, this.cal_items);
		setListAdapter(cal_adapter);
	}
	public final Handler notifyDataSetChanged = new Handler() {
		public void handleMessage(Message msg) {
			if (cal_adapter != null)
				cal_adapter.notifyDataSetChanged();
		}
	};
	
	public static void LoadCalEvent(Context context){
		String  contentProvider = "";
    	if(Build.VERSION.SDK_INT < 8){
    		contentProvider = "calendar";
    	} else {
    		contentProvider = "com.android.calendar";
    	}
    	
    	ContentResolver contentResolver = context.getContentResolver();
    	
    	Cursor eventCursor = contentResolver.query(Uri.parse("content://" + contentProvider +"/events"), 
				new String[]{ "_id", "title", "eventLocation", "description", "eventStatus",
								"dtstart", "dtend", "eventTimezone", "duration", "allDay",
								"hasAlarm", "rrule", "lastDate", "calendar_id" }, 
				null, null, null);
    	eventCursor.moveToFirst();
    	
    	Cursor remindCursor = contentResolver.query(Uri.parse("content://" + contentProvider + "/reminders"),
    			new String[]{ "_id", "event_id", "minutes", "method" }, null, null, null);
    	remindCursor.moveToFirst();
    	
    	eventCount = eventCursor.getCount();
		calCalendarIds = new String[eventCount];
		calEvents = new EventStruct[eventCount];
		
		int remindCount = (remindCursor.getCount()-1);
		int checkRemindSource = 0;
		for (int i = 0; i < eventCount; i++) {
			calEvents[i] = new EventStruct();
		    calEvents[i].uid = String.valueOf(eventCursor.getInt(eventCursor.getColumnIndexOrThrow("_id")));
		    calEvents[i].title = eventCursor.getString(eventCursor.getColumnIndexOrThrow("title"));
		    calEvents[i].event_location = eventCursor.getString(eventCursor.getColumnIndexOrThrow("eventLocation"));
		    calEvents[i].description = eventCursor.getString(eventCursor.getColumnIndexOrThrow("description"));
		    calEvents[i].status = String.valueOf(eventCursor.getInt(eventCursor.getColumnIndexOrThrow("eventStatus")));
		    calEvents[i].dtstart = String.valueOf(eventCursor.getInt(eventCursor.getColumnIndexOrThrow("dtstart")));
		    calEvents[i].dtend = String.valueOf(eventCursor.getInt(eventCursor.getColumnIndexOrThrow("dtend")));
		    calEvents[i].timezone = eventCursor.getString(eventCursor.getColumnIndexOrThrow("eventTimezone"));
		    calEvents[i].duration = eventCursor.getString(eventCursor.getColumnIndexOrThrow("duration"));
		    calEvents[i].allDay = String.valueOf(eventCursor.getInt(eventCursor.getColumnIndexOrThrow("allDay")));
		    calEvents[i].has_alarm = String.valueOf(eventCursor.getInt(eventCursor.getColumnIndexOrThrow("hasAlarm")));
		    calEvents[i].rrule = eventCursor.getString(eventCursor.getColumnIndexOrThrow("rrule"));
		    calEvents[i].last_date = String.valueOf(eventCursor.getInt(eventCursor.getColumnIndexOrThrow("lastDate")));
		    calCalendarIds[i] = String.valueOf(eventCursor.getInt(eventCursor.getColumnIndexOrThrow("calendar_id")));
		    
//		    if(checkRemindSource < remindCount){
//		    	RemainderStruct calReminder = new RemainderStruct();
//		    	while(calEvents[i].uid.equals(remindCursor.getString(1))){ 
//			    	calReminder.minutes = remindCursor.getString(2);
//			    	calReminder.method = remindCursor.getString(3);
//		    		calEvents[i].addReminderList(calReminder);
//			    	checkRemindSource++;
//			    	remindCursor.moveToNext();
//		    	}
//		    }
//		    if(calCalendarIds[i].equals("1")){
//			    calStruct.addEventList(calEvents[i]);
//		    }
		    eventCursor.moveToNext();
		}
		eventCursor.close();
		remindCursor.close();
	}
	
	private List<VCalendarList> ViewListCalendar(List<VCalendarList> cal_list){
		VCalendarList[] calList = new VCalendarList[eventCount];
		
		for (int i = 0; i < eventCount; i++) {
//			if(calCalendarIds[i].equals("1")){
			Date startDate = null;
			Date endDate = null;
			if(calEvents[i].dtstart != null){
				startDate = new Date(Long.parseLong(calEvents[i].dtstart));
			}
			if(calEvents[i].dtend != null){
				endDate = new Date(Long.parseLong(calEvents[i].dtend));
			} else {
				endDate = startDate;
			}
			dateString = TimeAdapter.Date2Str(startDate, "yyyy-MM-dd");
			String stDateString = TimeAdapter.Date2Str(startDate, "MM/dd hh:mmaa") + " - " + TimeAdapter.Date2Str(endDate, "MM/dd hh:mmaa");
			calList[i] = new VCalendarList(dateString, calEvents[i].title, stDateString, i);
			cal_list.add(calList[i]);
		}
		return cal_list;
	}
	public void updateTitleTextView(View textView, VCalendarList item) {
		((TextView)textView).setText(item.getTitle());
	}
	public void updateSubTitleTextView(View textView, VCalendarList item) {
		((TextView)textView).setText(item.getSubTitle());
	}
	
	private void makeSelectedCalendar() {
		VCalComposer composer2 = new VCalComposer();
        try {
        	vcalString = composer2.createVCal(calFileStruct, VCalComposer.VERSION_VCAL20_INT);
		} catch (VCalException e) {
			e.printStackTrace();
		}
		if(vcalString != null){
			
			String fileName = "";
			if(calEvents[0].title !=null && calEvents[0].title.equals("")){
				fileName = calEvents[0].title;
			}else{
				fileName = "vCalendar";
			}
			submitResult(vcalString, fileName);
		}else{
			toastStrId = R.string.toast_vcalendar_make_failed;
			finish();
		}
	}
	
	private Runnable sendCalendar = new Runnable(){
		public void run() {
			// TODO Auto-generated method stub
			makeSelectedCalendar();
		}
	};
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if(toastStrId != -1){
			Toast.makeText(ctx, toastStrId, Toast.LENGTH_SHORT).show();
//			toast.show();
		}
		super.onDestroy();
	}
}